// 获取域名映射出的 IP 地址

#include "error.h"
#include "sock.h"

#include <stdio.h>
#include <string.h>

#if defined(_WIN32)
#include <ws2tcpip.h>
#else
#include <netdb.h>
#endif

int
main(int argc, char **argv)
{
    if (argc != 2) {
        fprintf(stderr, "Usage: %s host-name\n", argv[0]);
        return 1;
    }
    const char *host = argv[1];

    sock_init();

    int code;
    struct addrinfo hints;
    struct addrinfo *result;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    if ((code = getaddrinfo(host, NULL, &hints, &result)) != 0)
        gai_error(code, "getaddrinfo fail");

    // 将 sockaddr 地址转换成字符串地址
    // 不指定 NI_NUMERICHOST 标志会导致转换变慢
    int flag = NI_NUMERICHOST;
    struct addrinfo *p = result;
    for (; p; p = p->ai_next) {
        char ip[100];
        if ((code = getnameinfo(p->ai_addr, p->ai_addrlen, ip, sizeof(ip), NULL, 0, flag)) != 0)
            gai_error(code, "getnameinfo fail");
        printf(":%s\n", ip);
    }

    freeaddrinfo(result);
    sock_cleanup();
    return 0;
}
